<template>
	<post-nav-bar title="个人信息"></post-nav-bar>
	<view class="blank"></view>
	<view class="userLayout pageBg">
		<view class="userInfo">
			<view class="content-wrapper">
				<u-form :model="userInfo" :rules="rules" ref="formRef">
					<!-- 头像上传 -->
					<u-form-item class="avatar-upload" label="头像" prop="profilePicture">
						<view @click="hanleAvatarUpload" class="userAvatarUpload">

							<!-- 使用 v-if 来判断是否有有效的图片 URL -->
							<image v-if="userInfo.profilePicture" :src="userInfo.profilePicture + '?t=' + Date.now()"
								class="avatar" mode="aspectFill" />
							<!-- 当没有提供 profilePicture 时，显示默认图片 -->
							<image v-else
								src="../../static/image/user/user.jpg"
								class="avatar" mode="aspectFill" />
							<!-- <view class="avatar">
			  	<image src=../../static/image/user/user.jpg mode="aspectFill"></image>
			  </view> -->
							<!-- 			  <u-icon v-else name="account-fill" size="80"></u-icon> -->
						</view>
						<text class="avatar-tip">点击修改头像</text>
					</u-form-item>

					<!-- 用户名 -->
					<u-form-item label="用户名" prop="username">
						<u-input v-model="userInfo.username" placeholder="请输入用户名" />
					</u-form-item>

					<!-- 手机号 -->
					<u-form-item label="手机号" prop="phone">
						<u-input v-model="userInfo.phone" placeholder="请输入手机号" type="number" />
					</u-form-item>

					<!-- 密码 -->
					<u-form-item label="密码" prop="password">
						<u-input v-model="userInfo.password" placeholder="请输入密码" :password="showPassword" type="text">
							<template #suffix>
								<u-icon :name="showPassword ? 'eye-off' : 'eye'"
									@click="showPassword = !showPassword" />
							</template>
						</u-input>
					</u-form-item>

					<!-- 简介 -->
					<u-form-item label="个人简介" prop="bio">
						<u-textarea v-model="userInfo.bio" placeholder="介绍一下自己吧" autoHeight />
					</u-form-item>

					<!-- 偏好 -->
					<u-form-item label="内容偏好" prop="preference">
						<u-textarea v-model="userInfo.preference" placeholder="请输入你的内容偏好" border="none" />
					</u-form-item>

					<view class="buttonbox">
						<u-button type="primary" text="保存修改" @click="handleSubmit" :loading="loading"
							customStyle="background-color: #FF4D4F; border-color: #FF4D4F" />
					</view>
				</u-form>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app' // 导入uniapp页面生命周期钩子
	import {
		appUrl
	} from '../../main';
	// 初始用户数据
	const initUserInfo = {
		username: "",
		phone: "",
		password: "",
		profilePicture: "",
		bio: "",
		preference: ""
	};

	const userInfo = reactive({
		...initUserInfo
	});
	const formRef = ref(null);
	const showPassword = ref(true);
	const loading = ref(false);
	const avatarList = ref([]);

	// 验证规则（保持原有规则不变）
	// 验证规则
	const rules = {
		username: [{
				required: true,
				message: '请输入用户名',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 12,
				message: '用户名长度2-12个字符',
				trigger: 'blur'
			}
		],
		phone: [{
				required: true,
				message: '请输入手机号',
				trigger: 'blur'
			},
			{
				pattern: /^1[3-9]\d{9}$/,
				message: '手机号格式不正确',
				trigger: 'blur'
			}
		]
	};


	const token = uni.getStorageSync("token")
	// 获取用户信息
	const fetchUserInfo = async () => {
		try {
			const res = await uni.request({
				url: appUrl + '/users/getUser',
				method: 'GET',
				header: {
					'token': token //自定义请求头信息
				}
			});

			if (res.statusCode === 200) {
				Object.assign(userInfo, res.data.data);
				avatarList.value = res.data.data.profilePicture ?
					[{
						url: res.data.data.profilePicture
					}] :
					[];
			}
		} catch (error) {
			uni.showToast({
				title: '获取信息失败',
				icon: 'error'
			});
		}
	};

	// 在组件挂载时获取用户信息
	onShow(() => {
		fetchUserInfo();
	});

	// 上传图片
	const hanleAvatarUpload = async () => {
		try {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: res => {
					var imageSrc = res.tempFilePaths[0];
					uni.showToast({
						icon: 'loading',
						title: "上传中",
						duration: 30000
					})
					uni.uploadFile({
						url: appUrl + '/users/upload/avatar', //仅为示例，非真实的接口地址
						filePath: imageSrc,
						fileType: 'image',
						name: 'image',
						header: {
							'token': uni.getStorageSync('token')
						},
						success: (res) => {
							uni.showToast({
								title: "成功",
							})
							console.log(res.data)
							const resData = JSON.parse(res.data);
							console.log(resData.data.profilePicture);
							userInfo.profilePicture = null;
							userInfo.profilePicture = resData.data.profilePicture;
						}
					});
				}
			});
		} catch (error) {
			uni.showToast({
				title: '获取信息失败',
				icon: 'error'
			});
		}
	};

	let filePath = ref('');

	const handleSelect = (e) => {
		filePath = e.tempFilePaths[0];
	}

	// 提交表单
	const handleSubmit = async () => {
		try {
			loading.value = true;
			await formRef.value.validate();

			// 提交更新请求
			const res = await uni.request({
				url: appUrl + '/users/updateUser',
				method: 'POST',
				header: {
					'token': uni.getStorageSync('token')
				},
				data: {
					...userInfo,
					// 如果接口需要其他参数可在此添加
				}
			});

			if (res.statusCode === 200) {
				uni.showToast({
					title: '修改成功',
					icon: 'success'
				});
				  console.log(token)
				  console.log(res.data.data.token)
				  uni.setStorageSync('token', res.data.data.token);
				  // 重新获取用户信息以确保数据最新
				  await fetchUserInfo();
				  // 可选：返回上一页
				  // uni.navigateBack();
			}
		} catch (error) {
			uni.showToast({
				title: error.errMsg || '修改失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};
</script>

<style lang="scss" scoped>
	.blank {
		height: 60rpx;
		background-color: ghostwhite;
		position: fixed;
		top: 70rpx;
		left: 0;
		width: 100%;
		z-index: 8;
	}
	
	.userLayout {
		width: 100%;
		height: 120vh;
		box-sizing: border-box;

		.userInfo {
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0 100rpx;

			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05); // 增加投影提升层次

			.content-wrapper {
				width: 90%;
				max-width: 750rpx;
				border-radius: 20rpx; // 统一圆角
				overflow: hidden;
			}

			// 头像区域强化
			.avatar-upload {
				width: 100%;
				margin: 80rpx 0;
				padding: 40rpx 0;
				background: linear-gradient(145deg, #f8f8f8, #ffffff); // 浅色渐变背景
				border-radius: 30rpx;
				box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.05);

				.avatar {
					width: 240rpx; // 适当放大头像
					height: 240rpx;
					border: 6rpx solid white; // 白色边框强化显示
					box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
					margin-bottom: 30rpx;
				}

				.avatar-tip {
					font-size: 26rpx;
					color: #999;
					letter-spacing: 2rpx;
				}
			}

			// 用户信息文字卡片
			.username,
			.userid,
			.address {
				width: 100%;
				padding: 30rpx 40rpx;
				margin: 20rpx 0;
				background: #f9f9f9;
				border-radius: 16rpx;
				border: 1rpx solid #eee; // 明确边框
				text-align: center;
				box-sizing: border-box;

				&::before {
					// 装饰性元素
					content: '';
					display: block;
					width: 60rpx;
					height: 4rpx;
					background: #ddd;
					margin: 0 auto 20rpx;
				}
			}

			.username {
				font-size: 46rpx;
				font-weight: 600;
				color: #333;
			}

			.userid {
				font-size: 30rpx;
				color: #666;
			}

			.address {
				font-size: 28rpx;
				color: #888;
			}
		}

		// 表单强化
		:deep(.u-form) {
			width: 90%;
			max-width: 750rpx;
			margin: 50rpx auto;
			background: white;
			border-radius: 20rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
			padding: 0 30rpx;

			.u-form-item {
				&__body {
					display: flex;
					align-items: center; // 垂直居中

					// 标签区域
					&__left {
						flex: 0 0 200rpx; // 固定标签宽度

						&__content__label {
							font-size: 30rpx;
							color: #606266;
							padding-right: 30rpx;
						}
					}

					// 输入区域
					&__right {
						flex: 1;
						min-width: 0;

						.u-input,
						.u-textarea {
							font-size: 30rpx;
							color: #303133;
							padding: 24rpx 0;

							// 统一输入框装饰线
							&__content__field-wrapper__field {
								&::after {
									border-bottom: 1rpx solid #dcdfe6 !important;
								}
							}
						}
					}

				}
			}

			// 文本域特殊处理
			.u-textarea {
				min-height: 180rpx;
				padding: 20rpx 0 !important;
			}
		}

		// 按钮容器优化
		.buttonbox {
			width: 90%;
			max-width: 750rpx;
			margin: 80rpx auto;
			padding: 40rpx 0 20rpx;
			background: white;
			border-radius: 20rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);

			:deep(.u-button) {
				width: 94%;
				margin: 0 auto;
				height: 100rpx;
				font-size: 34rpx;
				letter-spacing: 4rpx;
				transition: all 0.3s;

				&:active {
					transform: scale(0.98);
				}
			}
		}
	}
</style>